package com.sgb.kjwl.view.ui.activity.transport.owner;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityFreightCarTransportationBinding;
import com.sgb.kjwl.model.entity.transport.CarrierBusinessEntity;
import com.sgb.kjwl.model.entity.transport.TrucksCarrier;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity;
import com.sgb.kjwl.view.ui.activity.self.logistics.InquiryActivity;
import com.sgb.kjwl.view.ui.activity.transport.CarriageDetailActivity;
import com.sgb.kjwl.view.ui.adapter.transport.owner.FreightCarTransportationAdapter;
import com.sgb.kjwl.viewmodel.transport.FreightCarTransportationModel;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.event.EventConstant;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.PermissionCheckUtil;
import com.swgk.core.util.UserOperating;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author : 熊丽
 * @date :2021/4/12 0012$ 16:52$
 * @Description ://货车承运$2.0.4更名为：承运商机
 */
public class FreightCarTransportationActivity extends AppActivity implements View.OnClickListener {
    private ActivityFreightCarTransportationBinding mBinding;
    //货源列表
    private List<TrucksCarrier> mList;
    private FreightCarTransportationAdapter mAdapter;
    int page = 1;
    private FreightCarTransportationModel mModel;


    //跳转操作
    public static void start(Context context, boolean isGeneralGoods) {
        Intent intent = new Intent(context, FreightCarTransportationActivity.class);
        Bundle bundle = new Bundle();
        bundle.putBoolean(RouterKey.BOOLEAN, isGeneralGoods);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }
    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(FreightCarTransportationActivity.this, R.layout.activity_freight_car_transportation);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void init() {
        mModel = new ViewModelProvider(this).get(FreightCarTransportationModel.class);
        mBinding.includeTitle.ivBack.setOnClickListener(this);
        mBinding.includeTitle.titleView.setText("承运商机");
        inIt();
    }
    private void inIt(){
        initRecycler();
        initEvent();
        mModel.getList(this,1);
        mModel.mCarrierBusinessEntityMutableLiveData.observe(this, list -> {
            refreshUIByData(list);
        });
    }
    private void initRecycler() {
        mList = new ArrayList<>();
        mAdapter = new FreightCarTransportationAdapter(mList);
        mBinding.rvFragFreight.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter.bindToRecyclerView(mBinding.rvFragFreight);
    }

    private void initEvent() {
        mBinding.srlFragFreightCar.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page += 1;
                mModel.getList(FreightCarTransportationActivity.this,page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mModel.getList(FreightCarTransportationActivity.this,page);
            }
        });
        mAdapter.setListener(new FreightCarTransportationAdapter.GoodsOperationListener() {
            @Override
            public void OnitemClick(TrucksCarrier info) {
                CarriageDetailActivity.start(FreightCarTransportationActivity.this,info.getCarrierNo(),1);
            }

            @Override
            public void OnInquiryClick(TrucksCarrier info) {
                if (!ClickUtils.isDoubleClick()) {
                    if (UserOperating.getInstance().isNotOpenFundAccount(FreightCarTransportationActivity.this, PermissionCheckUtil.KEY_WODEXUNJIA)) {
                        return;
                    }
                    goInquiry(info);
                }
            }

            @Override
            public void CallPhone(TrucksCarrier info) {
                showConsignorDialog(info.getTelphone());
            }

            @Override
            public void goHome(TrucksCarrier info) {
                if (!TextUtils.isEmpty(info.getCompanyNo()) && info.getTerminal() != null && "1".equals(info.getTerminal())) {
                    WebsiteInfoActivity.start(FreightCarTransportationActivity.this, info.getCompanyNo(), WebsiteInfoActivity.WEBSITE_FOR_COMPANY);
                } else if (!TextUtils.isEmpty(info.getTeamNo()) && info.getTerminal() != null && "2".equals(info.getTerminal())) {
                    WebsiteInfoActivity.start(FreightCarTransportationActivity.this, info.getTeamNo(), WebsiteInfoActivity.WEBSITE_FOR_TEAM);
                } else {
                    WebsiteInfoActivity.start(FreightCarTransportationActivity.this, info.getUserNo(), WebsiteInfoActivity.WEBSITE_FOR_PERSONAL);
                }
            }
        });

    }
    /**
     * 同步数据
     */
    public void refreshUIByData(CarrierBusinessEntity listResponse) {
        mBinding.srlFragFreightCar.finishRefresh();
        mBinding.srlFragFreightCar.finishLoadMore();

        if (listResponse.getPage().getRecords() != null) {
            if (page==1){
                mList.clear();
            }
            mList.addAll(listResponse.getPage().getRecords());
        }
        if (listResponse.getPage().getPageNumber()>listResponse.getPage().getTotalPage()){
            mBinding.srlFragFreightCar.setNoMoreData(listResponse.getPage().isLastPage());
        }
        mAdapter.setEmptyView(R.layout.layout_null_list_logistics);
        mAdapter.notifyDataSetChanged();
    }
    private void goInquiry(TrucksCarrier info){
        //TODO 去询价界面
        InquiryActivity.startCarriageInquiry(this,info.getCarrierNo(),info.getTelphone());
    } //打电话弹窗
    public void showConsignorDialog(String phone) {
        new RoundDialog.Builder(this)
                .title("确认呼叫")
                .content(phone)
                .cancel("取消")
                .confirm("确定")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .confirmCallback(new RoundDialog.SingleCallback() {
                    @Override
                    public void onClick(View v) {
                        callPhone(phone);
                    }
                })
                .show();
    }
    protected void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        startActivity(intent);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
            finish();
            break;
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateCount(LogisticsEvent event) {
        switch (event.getMessageTag()) {
            case EventConstant.EVENT_REFRESH_INQUIRY:
                break;
            case EventConstant.EVENT_REFRESH_CAR_TRANSPORT:

                break;
        }
    }
}
